package com.example.easytts.controller

import com.example.easytts.service.DeepSeekService
import org.springframework.web.bind.annotation.*

@RestController
@RequestMapping("/api/deepseek")
class DeepSeekController(
    private val deepSeekService: DeepSeekService
) {
    data class GenerateRequest(
        val prompt: String,
        val model: String? = "deepseek-chat",
        val temperature: Double? = 0.7
    )

    data class GenerateResponse(
        val title: String,
        val content: String
    )

    @PostMapping("/generate")
    fun generateText(@RequestBody request: GenerateRequest): GenerateResponse {
        val formatTip = """
请你写一篇英文文章，主题如下，并以如下 JSON 格式输出：\n{\n  \"title\": \"文章标题\",\n  \"content\": \"文章内容\"\n}\n生成的文章内容要自动分段排版，每段开头内容需要缩进，不要输出任何多余的解释、提示或统计信息，只输出 JSON。\n主题：
""".trimIndent()
        val prompt = formatTip + (request.prompt.trim())
        val generatedText = deepSeekService.generateText(
            prompt = prompt,
            model = request.model ?: "deepseek-chat",
            temperature = request.temperature ?: 0.7
        )
        // 尝试解析JSON
        val objectMapper = com.fasterxml.jackson.module.kotlin.jacksonObjectMapper()
        val (title, content) = try {
            var jsonText = generatedText.trim()
            // 去除 markdown 代码块包裹
            if (jsonText.startsWith("```json")) {
                jsonText = jsonText.removePrefix("```json").removeSuffix("```").trim()
            } else if (jsonText.startsWith("```")) {
                jsonText = jsonText.removePrefix("```").removeSuffix("```").trim()
            }
            val node = objectMapper.readTree(jsonText)
            node["title"].asText() to node["content"].asText()
        } catch (e: Exception) {
            // fallback: 仍用原分割逻辑
            val lines = generatedText.lines().filter { it.isNotBlank() }
            val t = lines.firstOrNull()?.replace("**", "")?.trim() ?: ""
            val c = lines.drop(1).joinToString("\n").trim()
            t to c
        }
        return GenerateResponse(
            title = title,
            content = content
        )
    }
} 